﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public class RankSystem : ECSSystemtBase
{
    private RankComponent m_thisRank;

    public RankComponent rank
    {
        get {
            if (m_thisRank==null)
            {
                m_thisRank = MyWorld.GetSingletonComp<RankComponent>();
            }

            return m_thisRank;
        }
        set { m_thisRank = value; }
    }
    public override Type[] GetFilter()
    {
        return new Type[]
        {
            typeof(PlayerCom),
        };
    }

    public override void OnInit()
    {
         rank = MyWorld.GetSingletonComp<RankComponent>();
        MyWorld.eventSystem.AddListener(GameUtils.c_scoreChange,RecalcRank);
    }

    public override void OnDispose()
    {
       MyWorld.eventSystem.RemoveListener(GameUtils.c_scoreChange, RecalcRank);
    }
    /// <summary>
    /// 重计算rank分，改变rank单例组件的玩家数据
    /// </summary>
    /// <param name="entity"></param>
    /// <param name="objs"></param>
    public void RecalcRank(ECSEntityBase entity, params object[] objs)
    {
        List<ECSEntityBase> list = GetEntityList();

        list.Sort(sort);
        rank.randList.Clear();
        for (int i = 0,j=list.Count; i < j; i++)
        {
            rank.randList.Add(list[i].GetCom<PlayerCom>());
        }
    }

    static int sort(ECSEntityBase a, ECSEntityBase b)
    {
        PlayerCom aa = a.GetCom<PlayerCom>();
        PlayerCom bb = b.GetCom<PlayerCom>();
        if (aa.score>bb.score)
        {
            return -1;
        }

        if (aa.score<bb.score)
        {
            return 1;
        }

        return 0;
    }
}

